"""Check for unused artifacts in the AWS storage."""

import argparse
import os
import sys

from cki_lib import yaml
from cki_lib.gitlab import parse_gitlab_url
from cki_lib.logger import get_logger

from cki.cleaning_tools import s3bucketobjects
from cki.cleaning_tools.get_gitlab_data import GetMRsInfo

LOGGER = get_logger('cki.cleaning_tools.cleaning_tools')
S3_CONFIG = yaml.load(contents=os.environ.get('S3_CONFIG', ''))


class GitLabMergeRequestManager:
    """Class operates with Gitlab API using python gitlab library."""

    def __init__(self, gitlab_url):
        """
        Initialize project and git object.

        :param gitlab_url: Expected GitLab Project: https://gitlab.com/redhat/rhel/src/kernel/rhel-9
        """
        _, project = parse_gitlab_url(gitlab_url)
        self.git = GetMRsInfo(project)

    def get_git_merge_requests_by_period(self,
                                         created_after: str,
                                         created_before: str) -> dict:
        """
        Get all git and merge requests by time period.

        :param created_after: Expected in ISO 8601 format (2022-10-29T08:00:00Z)
        :param created_before: Expected in ISO 8601 format (2022-11-28T08:00:00Z)
        :return: A dictionary with integer values:
            - 'first_mr_id': an integer representing the first MR ID
            - 'last_mr_id': an integer representing the last MR ID
            - 'total_mrs': an integer representing the total number of MRs
        """
        period_mrs = self.git.get_merge_requests_by_period(
            created_after=created_after,
            created_before=created_before)
        LOGGER.info("Merged MRs by period from %s to %s", created_after, created_before)
        LOGGER.info(period_mrs)
        return period_mrs

    def calculate_total_bucket_size(self, mr_id: int):
        """
        Calculate the total size of all buckets associated with a list of MR pipelines.

        param: mr_pipelines (int): An merge request
        :return: None
        """
        mr_pipelines = self.git.get_merge_request_pipelines_before_the_last_succeed(mr_id)
        total_bucket_size = 0

        for pipeline in mr_pipelines:
            bridges_pipeline_ids = self.git.get_list_bridges_of_pipeline(pipeline['id'])
            bucket_url_size = s3bucketobjects.get_bucket_url_size(
                pipeline_ids=bridges_pipeline_ids, s3_config=S3_CONFIG)
            LOGGER.info("pipeline: %s", pipeline)
            for item in bucket_url_size['buckets']:
                LOGGER.info("%s %s %s", item['bucket_name'], item['url'], item['size'])
            total_bucket_size += bucket_url_size['total_size']
            LOGGER.info("TOTAL SIZE: %s", s3bucketobjects.convert_size(total_bucket_size))

    def get_pipelines_in_merged_merge_requests_before_the_last_succeed(self, merged_mrs):
        """
        Collect all together. This function basically pretty print to the output.

        :param merged_mrs: A dictionary with integer values:
            - 'first_mr_id': an integer representing the first MR ID
            - 'last_mr_id': an integer representing the last MR ID
            - 'total_mrs': an integer representing the total number of MRs
        :return: None
        """
        for mr_id in range(merged_mrs['first_mr_id'],
                           merged_mrs['last_mr_id']+1):
            if self.git.check_merge_request_state(mr_id, state='merged'):
                self.calculate_total_bucket_size(mr_id=mr_id)


def parse_arguments(arguments):
    """
    Parse command line arguments.

    :param arguments: command line arguments
    :return: Parsed arguments
    """
    parser = argparse.ArgumentParser()
    created_after_help = "Returns merge requests created on or after the given time. " \
                         "Expected in ISO 8601 format (2022-10-29T08:00:00Z)."
    created_before_help = "Returns merge requests created on or before the given time. " \
                          "Expected in ISO 8601 format (2022-11-28T08:00:00Z)."
    gitlab_url_help = "GitLab URL. Expected GitLab Project:" \
                      "    https://gitlab.com/redhat/rhel/src/kernel/rhel-9" \
                      "    https://gitlab.com/redhat/centos-stream/src/kernel/centos-stream-9"

    required = parser.add_argument_group('Required named arguments')
    required.add_argument("-a", "--created_after", help=created_after_help, required=True)
    required.add_argument("-b", "--created_before", help=created_before_help, required=True)
    required.add_argument("-u", "--gitlab_url", help=gitlab_url_help, required=True)

    return parser.parse_args(arguments)


if __name__ == "__main__":
    args = parse_arguments(sys.argv[1:])
    gl_request_manager = GitLabMergeRequestManager(args.gitlab_url)

    mrs_by_period = gl_request_manager.get_git_merge_requests_by_period(
        created_after=args.created_after,
        created_before=args.created_before)
    gl_request_manager.get_pipelines_in_merged_merge_requests_before_the_last_succeed(
        merged_mrs=mrs_by_period)
